
/*
Copyright 2009 Peter Ekler, Akos Ludanyi, Budapest University of Technology and Economics, Department of Automation and Applied Informatics, Applied Mobile Research Group (AMORG) http://amorg.aut.bme.hu

This file is part of MobTorrent.

MobTorrent is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

MobTorrent is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with MobTorrent.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package data;

import TorrentEngine.MTTorrent;
import TorrentEngine.Statistics;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Date;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordFilter;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotFoundException;

/**
 *
 * @author Ludányi Ákos
 */
public class MEStatistics extends Statistics {
    private final static String rmsDBName = "MobTorrentStats";
    
    private final int HEADER = 0;
    private final int CURRENT_VERSION = 1;

    /**IMEI query strings.*/
    private final static String [] imeiQuery = new String[]
    {
        "phone.imei",
        "com.nokia.IMEI",
        "com.sonyericsson.imei",
        "IMEI",
        "com.motorola.IMEI",
        "com.samsung.imei",
        "com.siemens.imei"
    };

    private String phoneID;
    private boolean registered;

    /**
     * Tries to load the ID, or generate one.
     */
    public MEStatistics()
    {
        try
        {
            phoneID = loadIDFromRMS();
            registered = true;
        }
        catch(Exception e)
        {
            phoneID = generateID();
            registered = false;
        }
    }

    private class HeaderFilter implements RecordFilter {
        public boolean matches(byte[] candidate)
        {
            try
            {
                DataInputStream ds = new DataInputStream(new ByteArrayInputStream(candidate));
                int type = ds.readInt();
                ds.close();
                return type == HEADER;
            }
            catch(Exception e)
            {
                return false;
            }
        }
    }

    private String loadIDFromRMS() throws Exception
    {
       RecordStore store = RecordStore.openRecordStore(rmsDBName, false);
       RecordEnumeration en = store.enumerateRecords(new HeaderFilter(), null, true);
       byte [] data = en.nextRecord();

       DataInputStream ds = null;
       ByteArrayInputStream bs = null;

       try
       {
           ds = new DataInputStream(bs = new ByteArrayInputStream(data));
           /*int header =*/ ds.readInt();
           final int version = ds.readInt();

           if(version != CURRENT_VERSION)
           {
               throw new Exception("Wrong version.");
           }

           final int length = ds.readInt();
           if(length <= 0)
           {
               throw new Exception("Invalid length");
           }

           StringBuffer id = new StringBuffer(length);
           for(int i = 0; i < length; i++)
           {
               id.append(ds.readChar());
           }

           return id.toString();
       }
       catch(Exception e)
       {
           try
           {
               ds.close();
           }
           catch(Exception e2)
           {
           }
           try
           {
               bs.close();
           }
           catch(Exception e2)
           {
           }
           throw e;
       }
    }

    private String generateID()
    {
        for(int i = 0; i < imeiQuery.length; i++)
        {
            final String res = System.getProperty(imeiQuery[i]);
            if(res != null)
                return res;
        }

        //No imei was found use the date.
       return "DATE" + String.valueOf(new Date().getTime());
    }

    public boolean isFirstTime()
    {
        return !registered;
    }

    public void onPhoneRegistered()
    {
        DataOutputStream ds = null;
        ByteArrayOutputStream bs = null;
        RecordStore rs = null;
        try
        {
            bs = new ByteArrayOutputStream();
            ds = new DataOutputStream(bs);
            ds.writeInt(HEADER);
            ds.writeInt(CURRENT_VERSION);
            ds.writeInt(phoneID.length());
            ds.writeChars(phoneID);
            byte [] data = bs.toByteArray();
            bs.close();
            ds.close();

            try
            {
                RecordStore.deleteRecordStore(rmsDBName);
            }
            catch(RecordStoreNotFoundException e)
            {
            }
            rs = RecordStore.openRecordStore(rmsDBName, true);


            rs.addRecord(data, 0, data.length);
            registered = true;
        }
        catch(Exception e)
        {
        }
        finally
        {
            try
            {
                rs.closeRecordStore();
            }
            catch(Exception e)
            {
            }
        }
    }

    public String getPhoneID()
    {
        return phoneID;
    }
}


